package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.Page;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.RemovalCjFrTableFieldEnum;
import com.py.credit.entity.enums.RemovalCjZrrTableFieldEnum;
import com.py.credit.entity.enums.RemovalJlFrTableFieldEnum;
import com.py.credit.entity.enums.RemovalJlZrrTableFieldEnum;
import com.py.credit.service.FeedbackService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.OfficeService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/feedback")
public class FeedbackController {

    private final static String FRONT_TABLE_FEEDBACK_CJFR_ID = "feedbackcjfr";

    private final static String FRONT_TABLE_FEEDBACK_CJZRR_ID = "feedbackcjzrr";

    private final static String FRONT_TABLE_FEEDBACK_JLFR_ID = "feedbackjlfr";

    private final static String FRONT_TABLE_FEEDBACK_JLZRR_ID = "feedbackjlzrr";

    @Autowired
    private FeedbackService feedbackService;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private OfficeService officeService;

    /**
     * 联合奖惩反馈普通检索
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @param type 主体类型：C：法人 P:自然人
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult getOptionalColums(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                               @RequestParam(value = "type", defaultValue = "", required = true) String type) {
        if (jclb.equals("C") && type.equals("C")) {
            return new RestServiceResult(RemovalCjFrTableFieldEnum.getOptionalColumns());
        } else if (jclb.equals("C") && type.equals("P")) {
            return new RestServiceResult(RemovalCjZrrTableFieldEnum.getOptionalColumns());
        } else if (jclb.equals("J") && type.equals("C")) {
            return new RestServiceResult(RemovalJlFrTableFieldEnum.getOptionalColumns());
        } else {
            return new RestServiceResult(RemovalJlZrrTableFieldEnum.getOptionalColumns());
        }
    }

    /**
     * 联合奖惩反馈高级检索
     *
     * @param jclb 奖惩类别：C:惩戒 J:激励
     * @param type 主体类型：C：法人 P:自然人
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult getAdvancedConditionColumns(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                                         @RequestParam(value = "type", defaultValue = "", required = true) String type) {
        if (jclb.equals("C") && type.equals("C")) {
            return new RestServiceResult(RemovalCjFrTableFieldEnum.getAdvancedConditionColumns());
        } else if (jclb.equals("C") && type.equals("P")) {
            return new RestServiceResult(RemovalCjZrrTableFieldEnum.getAdvancedConditionColumns());
        } else if (jclb.equals("J") && type.equals("C")) {
            return new RestServiceResult(RemovalJlFrTableFieldEnum.getAdvancedConditionColumns());
        } else {
            return new RestServiceResult(RemovalJlZrrTableFieldEnum.getAdvancedConditionColumns());
        }
    }

    /**
     * 联合奖惩反馈查询分页列表
     *
     * @param jclb      奖惩类别：C:惩戒 J:激励
     * @param type      主体类型：C：法人 P:自然人
     * @param condition 搜索条件
     * @param page      分页条件
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.json")
    public RestServiceResult getList(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                     @RequestParam(value = "type", defaultValue = "", required = true) String type,
                                     @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                                     Page page, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        List<String> showColumns = null;
        String deptId = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                deptId = officeService.selectTopDeptId(userInfo.getOfficeId() + "");

                if (jclb.equals("C") && type.equals("C")) {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_CJFR_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? RemovalCjFrTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                } else if (jclb.equals("C") && type.equals("P")) {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_CJZRR_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? RemovalCjZrrTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                } else if (jclb.equals("J") && type.equals("C")) {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_JLFR_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? RemovalJlFrTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                } else {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_JLZRR_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? RemovalJlZrrTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                }
            } else {
                ExceptionLogger.error("FeedbackController#getList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("FeedbackController#getList", "未获取到当前用户信息！");
        }

        String[] additionalColumns = {"id"};

        List<Map<String, Object>> integratedQuery = feedbackService.selectByConditionForPage(deptId, jclb, type, showColumns, additionalColumns, condition, page);

        return new RestServiceResult(page.getTotalCount(), integratedQuery);
    }

    /**
     * 联合奖惩反馈
     *
     * @param ajbh         事件编号
     * @param feedbackTime 反馈时间
     * @param feedbackMess 反馈信息
     * @param cfbm         处罚部门
     * @param csIds        措施id(多个逗号拼接)
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add.json")
    public RestServiceResult add(@RequestParam(defaultValue = "", required = true, value = "ajbh") String ajbh,
                                 @RequestParam(defaultValue = "", required = true, value = "feedbackTime") String feedbackTime,
                                 @RequestParam(defaultValue = "", required = true, value = "feedbackMess") String feedbackMess,
                                 @RequestParam(defaultValue = "", required = true, value = "cfbm") String cfbm,
                                 @RequestParam(defaultValue = "", required = true, value = "csIds") String csIds,
                                 HttpServletRequest request
    ) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("FeedbackController#getList", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("FeedbackController#getList", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        if (feedbackTime.equals("0")) {
            feedbackTime = sdf.format(new Date());
        }

        feedbackService.addFeedback(ajbh, feedbackTime, feedbackMess, cfbm, Arrays.asList(csIds.split(",")), userInfo, HttpServletHelper.getUserToken(request));
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 自定义列表选项
     *
     * @param jclb    奖惩类别：C:惩戒，J:激励
     * @param type    主体类型：C：法人 P:自然人
     * @param columns 列表数组
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                                    @RequestParam(value = "type", defaultValue = "", required = true) String type,
                                                    @RequestParam(value = "columns", required = true) String[] columns,
                                                    HttpServletRequest request) {

        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                if (jclb.equals("C") && type.equals("C")) {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_CJFR_ID, columns);
                } else if (jclb.equals("C") && type.equals("P")) {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_CJZRR_ID, columns);
                } else if (jclb.equals("J") && type.equals("C")) {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_JLFR_ID, columns);
                } else {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_FEEDBACK_JLZRR_ID, columns);
                }

            } else {

                ExceptionLogger.error("FeedbackController#addShowColunms", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("FeedbackController#addShowColunms", "未获取到当前用户信息！");
        }

        return new RestServiceResult<String>();
    }

    /**
     * 高级检索文件导出
     *
     * @param jclb      奖惩类别：C:惩戒，J:激励
     * @param type      主体类型：C：法人 P:自然人
     * @param condition 查询条件
     * @param columnEN  字段名
     * @param page      分页条件
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/export.json")
    public RestServiceResult export(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                    @RequestParam(value = "type", defaultValue = "", required = true) String type,
                                    @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                                    @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
                                    HttpServletRequest request, HttpServletResponse response) throws IOException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("FeedbackController#export", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("FeedbackController#export", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        page.setLimit(1000);

        List<String> columns = JSONArray.parseArray(columnEN, String.class);

        List<Map<String, Object>> data = feedbackService.selectByConditionForPage(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), jclb, type, columns,
                null, condition, page);

        List<OptionalColumn> optionalColumns = null;

        String excelName = "";
        if (jclb.equals("C") && type.equals("C")) {
            optionalColumns = RemovalCjFrTableFieldEnum.getOptionalColumns();
            excelName = "法人联合惩戒反馈";
        } else if (jclb.equals("C") && type.equals("P")) {
            optionalColumns = RemovalCjZrrTableFieldEnum.getOptionalColumns();
            excelName = "自然人联合惩戒名单反馈";
        } else if (jclb.equals("J") && type.equals("C")) {
            optionalColumns = RemovalJlFrTableFieldEnum.getOptionalColumns();
            excelName = "法人联合激励名单反馈";
        } else {
            optionalColumns = RemovalJlZrrTableFieldEnum.getOptionalColumns();
            excelName = "自然人联合激励名单反馈";
        }

        ExcelUtil.downloadExcel(response, data, excelName, excelName, columns, optionalColumns);

        return new RestServiceResult(RestServiceResult.CODE_SUCCESS, "导出成功");
    }
    /**
     * 信用全景分析联合奖惩分析
     *
     * @return
     */
 
    @ResponseBody
    @RequestMapping(value = "/getCreditviewData.json")
    public RestServiceResult<List<List<Map<String, String>>>> getCreditviewData() {
    	//获取联合奖惩数据
    	List<List<Map<String, String>>> list = feedbackService.getCreditviewData();
    	return new RestServiceResult<List<List<Map<String, String>>>> (list);
        
    }
    /**
     * 信用全景分析查询企业联合奖惩情况
     *
     * @return
     */
 
    @ResponseBody
    @RequestMapping(value = "/getCreditviewLhjcData.json")
    public RestServiceResult<Map<String, String>> getCreditviewLhjcData(@RequestParam(value = "keyWord", defaultValue = "")String keyWord) {
    	//获取联合奖惩数据
    	Map<String, String> list = feedbackService.getCreditviewLhjcData(keyWord);
    	return new RestServiceResult<Map<String, String>> (list);
        
    }
    
}
